const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const Package = require('./Package');

// 定义DownloadStat模型
const DownloadStat = sequelize.define('DownloadStat', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  package_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: Package,
      key: 'id'
    },
    comment: '包ID'
  },
  date: {
    type: DataTypes.DATEONLY,
    allowNull: false,
    comment: '统计日期'
  },
  downloads: {
    type: DataTypes.BIGINT,
    defaultValue: 0,
    allowNull: false,
    comment: '当日下载量'
  }
}, {
  tableName: 'download_stats',
  indexes: [
    { name: 'idx_package_date', fields: ['package_id', 'date'], unique: true }
  ]
});

// 建立关系
Package.hasMany(DownloadStat, {
  foreignKey: 'package_id',
  as: 'download_stats'
});

DownloadStat.belongsTo(Package, {
  foreignKey: 'package_id',
  as: 'package'
});

module.exports = DownloadStat;